package domain;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.util.LinkedList;

import serializables.Song;

public class ReceivePlaylistThread extends Thread {

	private MulticastSocket mcListSocket;
	private DatagramPacket inPacket;
	private InetAddress group;
	private int port;

	public ReceivePlaylistThread(String address, int port) {
		try{
			this.port = port;
			mcListSocket = new MulticastSocket(port);
			group = InetAddress.getByName(address);
			mcListSocket.joinGroup(group);
		}catch (IOException e) {
			System.out.println("error joining playlist mc group: " + e);
		}
	}
	
	public void run(){
		
		while(true){
			try{
				if(mcListSocket.isClosed()){
					mcListSocket = new MulticastSocket(port);
					mcListSocket.joinGroup(group);
				}
				byte[] buf = new byte[256];
				inPacket = new DatagramPacket(buf, buf.length);
				mcListSocket.receive(inPacket);
				
				ByteArrayInputStream bais = new ByteArrayInputStream(buf);
				ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(bais));
				ClientDomainController.setSongs((LinkedList<Song>) ois.readObject());
				mcListSocket.leaveGroup(group);
				mcListSocket.close();
				
				
			}catch (IOException e) {
				System.out.println("error receiving playlist: "+e );
				System.out.println(e.getMessage() );
				System.out.println(e.getCause());
			} catch (ClassNotFoundException e) {
				System.out.println("class not found on receiving playist");
			}
		}
	
	}
	
	
}
